package com.fbli.test.config;

import com.alibaba.fastjson.JSON;
import com.fbli.test.common.result.ResultSend;
import com.fbli.test.entity.Authority;
import com.fbli.test.entity.Token;
import com.fbli.test.entity.User;
import com.fbli.test.service.AuthorityService;
import com.fbli.test.service.TokenService;
import com.fbli.test.service.UserService;
import com.fbli.test.util.JsonUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Resource
    UserService userService;
    @Resource
    TokenService tokenService;
    @Resource
    AuthorityService authorityService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        User user = (User) principalCollection.getPrimaryPrincipal();
        long id = user.getId();
        Set<String> permSet = new HashSet<>();
        Set<String> roleSet = new HashSet<>();
        if (user.getSuperAdmin()){
            //如果是超级管理员，获取所有权限，角色
            List<Authority> authorities = authorityService.selectAll();
            for (Authority authority:authorities){
                permSet.add(authority.getPerms());
                roleSet.add(authority.getRole());
            }
        }else {
            //普通用户,获取当前用户的权限，角色
            List<Authority> list = authorityService.selectByUserId(id);
            for (Authority authority:list){
                permSet.add(authority.getPerms());
                roleSet.add(authority.getRole());
            }
        }
        info.setStringPermissions(permSet);//添加权限
        info.setRoles(roleSet);//添加角色
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入验证");
        String principal =(String) token.getPrincipal();
        //验证token 判断是否过期
        Token userToken = tokenService.selectByToken(principal);
        if (userToken == null || userToken.getExpireTime() <= System.currentTimeMillis()) {
            throw new IncorrectCredentialsException(JsonUtil.INSTANCE.obj2json(ResultSend.send(100001, "token已失效！请重新登录！", null)));
        }
        //根据token获取用户数据
        User user = userService.selectByPrimaryKey(userToken.getUserId());
        if(user==null){
            throw  new IncorrectCredentialsException(JsonUtil.INSTANCE.obj2json(ResultSend.send(100002, "token验证失败！", null)));
        }
        //判断用户状态
        if (user.getDeleted() || !user.getState()) {
            throw new IncorrectCredentialsException(JsonUtil.INSTANCE.obj2json(ResultSend.send(100003, "用户账号已失效！", null)));
        }
        //密码认证，shiro做~
        return new SimpleAuthenticationInfo(user,principal,getName());
    }
}
